import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
    {path: '/', redirect: '/login'},
    {
        path: '/login',
        component: () => import('../components/login')
    },
    {   // 定义一个welcome子组件
        path: '/home',
        redirect: '/welcome',
        children: [
            {
                path: '/welcome',
                component: () => import('../components/welcome')
            },
            {
                path: '/users',
                component: () => import('../components/user/user')
            },
            {
                path: '/rights',
                component: () => import('../components/power/rights')
            },
            {
                path: '/roles',
                component: () => import('../components/power/roles')
            }
        ],
        component: () => import('../components/home')
    }

]

const router = new VueRouter({
    routes
});
// 挂在路由导航首位
// to: 将要访问的路径
// from: 从哪个路径跳转过来的
// next: 一个函数, 放行请求
router.beforeEach((to, from, next) => {
    // 如果用户访问的是登录页面
    if (to.path == '/login') return next();
    // 判断当前请求用户是否携带token
    const token = window.sessionStorage.getItem('token');
    if (!token) return next('/login');
    // 有token则放行
    next();
});


export default router
